package com.wqz.day19_redisdemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wqz.day19_redisdemo.entity.Student;
import com.wqz.day19_redisdemo.mapper.StudentMapper;
import com.wqz.day19_redisdemo.service.StudentService;
import com.wqz.day19_redisdemo.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.Map;

/**
 * (Student)表服务实现类
 *
 * @author 王乾州
 * @since 2025-10-20 19:39:15
 */
@Service("studentService")
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentMapper studentMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R addStudent(Student student) {
        // 添加学生,主键返回mybatis-plus已经自动集成了
        int insert = studentMapper.insert(student);
        // 将学生的存入到redis中

        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        // 将学生信息存入到redis缓存中,
        // 将学生对象转换成json字符串
        HashMap<String, String> map = new HashMap<>();
        map.put("name", student.getName());
        map.put("age", student.getAge().toString());
        map.put("sclass", student.getSclass());
        hashOperations.putAll("stu:"+ student.getId(), map);

        return R.success("添加学生成功!");
    }

    @Override
    public R selectStudentById(Long id) {
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        Map<String, String> stu = hashOperations.entries("stu:" + id);
        System.out.println(stu);
        // 根据传入的id从map集合中获取学生对象
//        String s = stu.get("name");
        // 判断从map集合中获取的学生对象
        Student student = null;
        if(stu.size() == 0) {
            // 集合中没有找到该id,说明该学生在redis储存的信息已经消失,或者是根本就没有,所以也需要查找一个数据库
            student = studentMapper.selectById(id);
            if(student == null) {
                // 没有找到,往redis中存入一个空字符串
                HashMap<String, String> map = new HashMap<>();
                map.put("null",null);
                hashOperations.putAll("stu:"+ id, map);
            } else {
                // 需要再次存一下,因为缓存已经消失了
                HashMap<String, String> map = new HashMap<>();
                map.put("name", student.getName());
                map.put("age", student.getAge().toString());
                map.put("sclass", student.getSclass());
                hashOperations.putAll("stu:"+ id, map);
            }
        } else {
            // 不需要解析
//            if(!"".equals(s)) {
//                student = JSONObject.parseObject(s, Student.class);
//            }
        }
        return R.success(stu);
    }
}
